package com.ncu.xrpc.zk;

import com.ncu.xrpc.ServiceRegistry;
import com.ncu.xrpc.constant.Contant;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;

/**
 * Created by IntelliJ IDEA.
 * User: xiongwb
 * Date: 2021/9/12 9:42
 * Describe: 具体实现服务注册(基于Zookeeper)
 */
@Slf4j
public class ZkServiceRegistry implements ServiceRegistry {

    private ZkClient zkClient;

    public ZkServiceRegistry(String zkAddress){
        this.zkClient = new ZkClient(zkAddress, Contant.ZK_SESSION_TIMEOUT, Contant.ZK_CONNECTION_TIMEOUT);
        log.info("初始化zookeeper完成(ZkServiceRegistry)");
    }

    /**
     * @param serviceName  服务名称
     * @param serviceAddress 服务地址
     */
    @Override
    public void register(String serviceName, String serviceAddress) {
        //创建 持久 registry节点  /XRpc-registry
        String registryPath = Contant.ZK_REGISTRY_PATH;
        if(!zkClient.exists(registryPath)){
            zkClient.createPersistent(registryPath);
            log.info("successful create registry node :"+registryPath);
        }

        //创建 持久 service 节点    /XRpc-registry / serviceName
        String servicePath = registryPath + "/" + serviceName;
        if(!zkClient.exists(servicePath)){
            zkClient.createPersistent(servicePath);
            log.info("successful create service node :"+servicePath);
        }

        //创建 临时 address 节点
        String addressPath = servicePath + "/address-";

        //创建临时 address 节点 并且将 serviceAddress作为数据放到address 节点内
        zkClient.createEphemeralSequential(addressPath,serviceAddress);

        log.info("successful create address node :"+addressPath+",serviceAddress is"+serviceAddress);

    }
}
